package com.masterclient.app.modules.income.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.masterclient.app.R;
import com.masterclient.app.modules.income.model.WithdrawChargeBean;
import com.masterclient.app.utils.CaptchaUtil;
import com.eoner.uikit.edits.CodeEditView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 作者：sean
 * 创建时间：2017/9/5 10:18
 * 功能说明：
 */
public class ApplyWithdrawDialog extends Dialog implements View.OnClickListener {


    private final Context mContext;
    private final WithdrawChargeBean withdrawChargeBean;
    private TextView tvTitle;
    private View viewApplyWithdrawDetails;
    private View viewCode;
    private TextView tvPhoneTxt;
    private TextView tvCodeTxt;
    private TextView tvWithdraw;
    private CodeEditView codeEditView;

    SPUtils spUtils;
    CountDownTimer timer;
    long verifyTime;
    private CaptchaUtil captchaUtil;
    private String captcha;

    public ApplyWithdrawDialog(@NonNull Context context, WithdrawChargeBean withdrawChargeBean) {
        super(context, R.style.MyDialog);
        mContext = context;
        this.withdrawChargeBean = withdrawChargeBean;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_apply_withdraw);
        setCanceledOnTouchOutside(true);

        viewApplyWithdrawDetails = findViewById(R.id.view_apply_withdraw_details);
        tvTitle = findViewById(R.id.tv_title);
        TextView tvAccount = findViewById(R.id.tv_account);
        TextView tvAccountCharge = findViewById(R.id.tv_account_charge);
        View viewDes = findViewById(R.id.view_des);
        TextView tvDes = findViewById(R.id.tv_des);

        viewCode = findViewById(R.id.view_code);
        tvPhoneTxt = findViewById(R.id.phone_txt);
        codeEditView = findViewById(R.id.codeEditView);
        tvCodeTxt = findViewById(R.id.get_code_txt);
        tvWithdraw = findViewById(R.id.tv_withdraw);

        findViewById(R.id.iv_cancel).setOnClickListener(this);
        findViewById(R.id.tv_confirm).setOnClickListener(this);
        findViewById(R.id.tv_withdraw).setOnClickListener(this);
        findViewById(R.id.get_code_txt).setOnClickListener(this);

        tvWithdraw.setClickable(false);
        tvWithdraw.setBackgroundResource(R.drawable.shape_radius24_f0f2f5);
        viewApplyWithdrawDetails.setVisibility(View.VISIBLE);
        viewCode.setVisibility(View.GONE);
        tvAccount.setText(String.format("%s元", withdrawChargeBean.withdrawAmount));
        tvAccountCharge.setText(String.format("%s元", withdrawChargeBean.withdrawChargeAmount));
        if (!TextUtils.isEmpty(withdrawChargeBean.withdrawDesc)) {
            tvDes.setText(withdrawChargeBean.withdrawDesc.replace("\\n", "\n"));
            viewDes.setVisibility(View.VISIBLE);
        } else {
            viewDes.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        window.setWindowAnimations(R.style.bottomShow);
        WindowManager.LayoutParams windowParams = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        windowParams.height = (int) (ScreenUtils.getScreenHeight() * 0.58);
        windowParams.width = ScreenUtils.getScreenWidth();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(windowParams);
    }

    public void setViewCodePage() {
        tvTitle.setText("短信验证码");
        viewApplyWithdrawDetails.setVisibility(View.GONE);
        viewCode.setVisibility(View.VISIBLE);

        init();
        initViews();
        addListener();
    }

    private void addListener() {
        codeEditView.setOnCodeFinishListener(code -> {
            captcha = code;
            tvWithdraw.setClickable(true);
            tvWithdraw.setBackgroundResource(R.drawable.shape_radius24_fc2a52);
        });
        codeEditView.setOnCodeUnFinishListener(() -> {
            tvWithdraw.setClickable(false);
            tvWithdraw.setBackgroundResource(R.drawable.shape_radius24_f0f2f5);
        });
    }

    private void init() {
        captchaUtil = new CaptchaUtil(mContext, "验证码登录");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                onGetCaptchaClickListener.getCaptchaClickListener(withdrawChargeBean.mobile);
            }

            @Override
            public void onFailed() {
                tvCodeTxt.setClickable(true);
            }
        });


        spUtils = SPUtils.getInstance();
        verifyTime = spUtils.getLong(Config.APPLY_WITHDRAW_VERIFY_TIME);
        if (verifyTime > 0 && System.currentTimeMillis() - verifyTime < 60 * 1000) {
            tvPhoneTxt.setClickable(false);
            timer = new CountDownTimer((60 * 1000) - (System.currentTimeMillis() - verifyTime), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    String timeStr = millisUntilFinished / 1000 + "s";
                    String temp = timeStr + "重新发送验证码";

                    SpannableString spannableString = new SpannableString(temp);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tvCodeTxt.setText(spannableString);
                    tvCodeTxt.setBackgroundResource(0);
                }

                @Override
                public void onFinish() {
                    tvCodeTxt.setClickable(true);
                    String timeStr = "重新发送验证码";
                    tvCodeTxt.setBackgroundResource(R.drawable.text_underline_397be6);

                    SpannableString spannableString = new SpannableString(timeStr);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tvCodeTxt.setText(spannableString);
                }
            };
            timer.start();
        }
    }

    Timer softInputTimer;

    private void initViews() {
        tvPhoneTxt.setText(String.format("已向您的尾号%s的手机发送验证码", withdrawChargeBean.mobile.substring(withdrawChargeBean.mobile.length() - 4, withdrawChargeBean.mobile.length())));
        tvCodeTxt.setClickable(false);

        softInputTimer = new Timer();
        softInputTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (codeEditView != null) {
                        codeEditView.showSoftInput(null);
                    }
                });
            }

        }, 100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                onGetCaptchaClickListener.getCaptchaClickListener(withdrawChargeBean.mobile);
                break;
            case R.id.tv_withdraw:
                onGetCaptchaClickListener.submitClickListener(withdrawChargeBean.mobile, captcha);
                break;
            case R.id.get_code_txt:
                codeEditView.clear();
                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                        onGetCaptchaClickListener.getCaptchaClickListener(withdrawChargeBean.mobile);
                    } else {
                        captchaUtil.start();
                    }
                } else {
                    onGetCaptchaClickListener.getCaptchaClickListener(withdrawChargeBean.mobile);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public interface OnGetCaptchaClickListener {
        void getCaptchaClickListener(String phoneNum);

        void submitClickListener(String phoneNum, String captcha);
    }

    private OnGetCaptchaClickListener onGetCaptchaClickListener;

    public void setOnGetCaptchaClickListener(OnGetCaptchaClickListener onGetCaptchaClickListener) {
        this.onGetCaptchaClickListener = onGetCaptchaClickListener;
    }
}
